<template>
    <view :class="$t('dir') == 'rtl' ? 'rtl' : 'ltr'">
        <!--  验证码-弹出层  -->
        <u-popup :show="showCodeLogin" mode="center" @close="close" bgColor="transparent" customStyle="max-width:780px;margin:0 auto;margin-top:13vh !important;" :zIndex="notagreeShow ? 1000 : 10075" :overlayOpacity="notagreeShow ? '0' : '0.5'">
            <view class="text-center pt-lg p-relative popup-box">
                <view class="text-center fs-xs px-lg mt-sm">{{ $t('login_tost') }}</view>
                <view v-if="!wechatLoginStatus">
                    <view class="text-gray mt-lg mb-xs"> {{ $t('plechold_phone') }} </view>
                    <view class="dir-ltr center pa-sm row items-center" style="background: #f9f9f9; border-radius: 68rpx; width: 76%; margin: 0 auto" :style="checkPwdStatus ? 'padding-top: 22rpx;padding-bottom: 20rpx' : ''">
                        <view class="mx-sm">
                            <u-icon name="phone-fill" size="40rpx" color="#a5a4a4" />
                        </view>
                        <input type="number" v-model="phone" maxlength="11" shape="circle" border="none" clearable placeholderStyle="text-align:center !important;font-size:24rpx;color:#8a989d" :customStyle="{ textAlign: 'center !important', letterSpacing: '4rpx' }" color="grey" fontSize="36rpx" @input="changePhone" />
                        <button v-if="!checkPwdStatus" :disabled="disabled" class="code-button" @click="handleButtonClick">
                            <text>{{ countDown > 0 ? `(${countDown}s)` : '' }}</text>
                            <text class="px-xs d-inline-block" :class="countDown > 0 ? '' : 'mx-sm'" style="min-width: 60rpx">{{ $t('send') }}</text>
                        </button>
                    </view>

                    <view class="text-gray mt-lg mb-xs"> {{ checkPwdStatus ? $t('qingshurumima') : $t('plechold_Captcha') }} </view>

                    <view v-if="checkPwdStatus" class="dir-ltr center pa-sm row items-center" style="background: #f9f9f9; border-radius: 68rpx; width: 76%; margin: 0 auto; border: 1px solid #f2f2f2; padding-top: 26rpx; padding-bottom: 24rpx">
                        <view class="mx-sm">
                            <u-icon :name="pwdShow ? 'eye-off' : 'eye-fill'" size="40rpx" color="#a5a4a4" @click="pwdShow = !pwdShow" />
                        </view>

                        <input v-if="pwdShow" type="text" v-model="password" style="flex: 1" maxlength="20" shape="circle" border="none" clearable placeholderStyle="text-align:center !important;font-size:28rpx;color:#8a989d;letterSpacing: 0rpx" :customStyle="{ textAlign: 'center !important', letterSpacing: '2rpx', fontSize: '36rpx', color: 'grey' }" />
                        <input v-else :password="true" type="password" v-model="password" style="flex: 1" maxlength="20" shape="circle" border="none" clearable placeholderStyle="text-align:center !important;font-size:28rpx;color:#8a989d;letterSpacing: 0rpx" :customStyle="{ textAlign: 'center !important', letterSpacing: '2rpx', fontSize: '36rpx', color: 'grey' }" />

                        <!-- <input :type="pwdShow ? 'text' : 'password'" v-model="password" style="flex: 1" maxlength="20" shape="circle" border="none" clearable placeholderStyle="text-align:center !important;font-size:28rpx;color:#8a989d;letter-spacing: 0rpx" :customStyle="{ textAlign: 'center !important', letterSpacing: '2rpx', fontSize: '36rpx', color: 'grey' }" :password-icon="true" /> -->
                        <view class="text-red" style="width: 132rpx; border-left: 1rpx solid #ccc; margin-left: 12rpx" @click="goToForgetPwd">{{ $t('wangjimima') }}</view>
                    </view>

                    <template v-else>
                        <view class="dir-ltr ltr pa-sm d-flex flex-center" style="background: #f9f9f9; border-radius: 68rpx; width: 76%; margin: 0 auto">
                            <verify-code-input :maxLength="codeLength" @change="handleCodeChange" />
                        </view>
                    </template>
                </view>

                <!--密码登录/验证码登录切换 -->
                <view v-if="!wechatLoginStatus" class="pa-sm row flex-center text-gray mt-sm" @click="checkPwdStatus = !checkPwdStatus">
                    <text class="mx-xs">{{ checkPwdStatus ? $t('duanxinyanzhengmadenglu') : $t('mimadenglv') }}</text>
                    <image style="width: 36rpx; height: 36rpx" src="/static/images/index/qiehuan.svg"></image>
                </view>

                <view class="full-width fs-xs mt-lg mb-md">
                    <!-- 登录按钮 -->
                    <view v-if="!wechatLoginStatus">
                        <button :disabled="phone.length == 11 && (checkPwdStatus ? password.length > 5 : code.length == codeLength) ? false : true" class="d-inline-block login-button mb-md" @click="_userLogin">
                            {{ $t('login') }}
                        </button>
                    </view>
                    <!-- <view v-if="checkPwdStatus" class="text-white d-inline-block bg-red login-button mb-md" @click="_userLogin">{{ $t('login1') }}</view><br /> -->

                    <!-- 微信登录 -->
                    <!-- #ifdef MP-WEIXIN -->
                    <view class="row flex-center mb-lg dir-rtl">
                        <view class="text-white d-inline-block wechat-login-btn wx-button p-relative button" style="background: #f9f9f9" @click="phoneLogin">
                            <button open-type="getPhoneNumber" @getphonenumber="phonenumber" v-if="select"></button>
                            <view class="row flex-center">
                                <view>
                                    <u-icon name="weixin-fill" size="26px" color="#42b600" />
                                </view>
                                <text style="color: #42b600" class="mx-xs fs-md"> {{ $t('logByWechat') }} </text>
                            </view>
                        </view>
                        <image @click="wechatLoginStatus = !wechatLoginStatus" style="width: 40rpx; height: 40rpx; margin-left: -22px; margin-right: 12px" src="/static/images/index/qiehuan.svg"></image>
                    </view>

                    <!-- #endif -->

                    <!-- 用户协议 -->
                    <view class="my-md">
                        <view :style="{ visibility: checkPwdStatus ? 'hidden' : '' }" style="font-size: 22rpx">{{ $t('unregisteredMobilePhoneNumbersWillBeAutomaticallyRegisteredByCheckingThisBoxYouReadAndAgree') }}</view>
                        <view class="d-flex flex-center mt-xs">
                            <view class="row pa-xs">
                                <u-icon v-if="select" @click="select = false" name="checkmark-circle-fill" size="40rpx" color="red"></u-icon>
                                <i v-else @click="select = true" class="radio-i" :class="{ shakeonce: shakeOnce }"></i>
                            </view>
                            <text class="text-red" @click="goToPath('/pages/my-data/content?type=privacyPolicy')">《{{ $t('privacyPolicy') }}》</text>{{ $t('and') }}<text class="text-red" @click="goToPath('/pages/my-data/content')">《{{ $t('userAgreement') }}》</text><text>{{ $t('iAgree') }}</text>
                        </view>
                    </view>
                </view>
            </view>
        </u-popup>

        <custom-modal :show="notagreeShow" @close="notagreeShow = false" :customContent="true" @confirm="notagreeConfirm">
            <template v-slot:content>
                <view class="row flex-center my-md flex-wrap" :style="{ direction: $t('dir') }">
                    <text class="text-red" @click="goToPath('/pages/my-data/content?type=privacyPolicy')">《{{ $t('privacyPolicy') }}》</text>{{ $t('and') }} <text class="text-red" @click="goToPath('/pages/my-data/content')">《{{ $t('userAgreement') }}》</text><text>{{ $t('iAgree') }}</text>
                </view>
            </template>
        </custom-modal>
    </view>
</template>
<script>
const app = getApp()
export default {
    name: 'login-popup',
    props: {
        show: {
            type: Boolean,
            default: false,
        },
    },
    data() {
        return {
            select: false,
            checkPwdStatus: false,
            code: '',
            timer: null,
            countDown: 0,
            buttonTimeout: 60,
            disabled: true,
            notagreeShow: false,
            phone: '',
            password: '',
            codeLength: 6,
            development: false,
            showCodeLogin: false,
            pwdShow: false,
            shakeOnce: false,
            wechatLoginStatus: false,
        }
    },
    created(){
        var qrCode = uni.getStorageSync('kefu')
        console.log('qrCode',qrCode)
    },
    watch: {
        show(newValue, oldValue) {
            this.getOpenid()
            // #ifdef MP-WEIXIN
            this.wechatLoginStatus = true
            // #endif
            // #ifndef MP-WEIXIN
            this.wechatLoginStatus = false
            // #endif

            var development = process.env.NODE_ENV === 'development'
            this.development = development
            if (newValue) {
                // if (development)
                this.showCodeLogin = true
                // else this.oneClickLoginShow()
            } else {
                this.showCodeLogin = false
            }
        },
    },
    mounted() {
        var development = process.env.NODE_ENV === 'development'
        this.development = development
    },
    methods: {
        phoneLogin() {
            if (!this.select) {
                uni.showToast({
                    title: this.$t('qinngtongyifuwutiaokuan'),
                    duration: 2000,
                    icon: 'none',
                })
                this.shakeOnce = true
                setTimeout(() => {
                    this.shakeOnce = false
                }, 800)
            }
        },
        /* 获取手机号码 */
        phonenumber(res) {
            console.log('phonenumber:', res)
            let { encryptedData, iv, code } = res.detail
            let param = {
                encryptedData,
                iv,
                session_key: uni.getStorageSync('session_key'),
                openid: uni.getStorageSync('openid'),
                parent_id: uni.getStorageSync('parent_id') || '',
                type: uni.getStorageSync('type') || '',
            }
            this.$uniapi('/getPhone', param, 'post')
                .then((res) => {
                    if (res.code == 0) {
                        this.loginHandle(res.data)
                    } else {
                        uni.showToast({
                            title: res.msg,
                            duration: 2000,
                            icon: 'none',
                        })
                    }
                })
                .catch((err) => {})
        },
        close(e) {
            this.$emit('close')
        },

        getOpenid() {
            // #ifdef MP-WEIXIN
            let that = this
            wx.login({
                success: function (t) {
                    var o = t.code
                    that.$uniapi(
                        '/getOpenid',
                        {
                            code: o,
                        },
                        'POST'
                    ).then((res) => {
                        if (res.code == 0) {
                            if (res.data.data.session_key) uni.setStorageSync('session_key', res.data.data.session_key)
                            if (res.data.data.openid) uni.setStorageSync('openid', res.data.data.openid)
                        }
                    })
                },
            })
            // #endif
        },

        handleCodeChange(code) {
            // 验证码输入框的值发生变化
            this.code = code
        },

        handleButtonClick() {
            if (!this.phone || !this.checkMobileNum(this.phone)) {
                uni.showToast({
                    title: this.$t('pleaseEnterAValidMobilePhoneNumber'),
                    icon: 'none',
                    duration: 2000,
                })
                return
            }
            if (this.countDown > 0) return

            this._userSendcode()
        },

        // 获取验证码
        async _userSendcode() {
            uni.showLoading({
                title: '',
            })
            await this.$uniapi(
                '/getMobileCode',
                {
                    mobile: this.phone,
                },
                'post'
            )
                .then((res) => {
                    uni.hideLoading()
                    if (res.code == 0) {
                        this.countDown = this.buttonTimeout
                        this.disabled = true

                        this.timer = setInterval(() => {
                            if (this.countDown > 0) {
                                this.countDown--
                            } else {
                                clearInterval(this.timer)
                                this.disabled = false
                            }
                        }, 1000)
                        this.$emit('get-verify-code')
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none',
                            duration: 2000,
                        })
                    }
                })
                .catch((err) => {
                    uni.hideLoading()
                    uni.showToast({
                        title: err.errMsg,
                        duration: 2000,
                        icon: 'none',
                    })
                })
        },

        goToPath(url) {
            uni.navigateTo({
                url: url,
            })
        },

        //确认
        notagreeConfirm() {
            this.select = true
            this._userLogin()
            this.notagreeShow = false
        },

        // 检查手机号格式
        checkMobileNum(phone) {
            let reg = /^(\+86)?(1[3-9][0-9])[0-9]{8}$/
            if (reg.test(phone)) {
                console.log('手机号格式正确')
                return true
            }
            // '手机号格式不正确'
            else return false
        },

        // 输入手机号
        changePhone(e) {
            let val = e.detail.value
            if (val.length == 11) this.disabled = false
            else this.disabled = true
        },

        goToForgetPwd() {
            uni.navigateTo({
                url: '/pages/settings/forget-pwd',
            })
        },

        //一键登录
        oneClickLoginShow() {
            uni.showLoading({
                mask: true,
            })
            uni.preLogin({
                provider: 'univerify',
                success: () => {
                    //预登录成功 - 显示一键登录选项
                    console.log('预登录成功')
                    uni.hideLoading()

                    uni.login({
                        provider: 'univerify',
                        univerifyStyle: {
                            // 自定义登录框样式 ,参考`univerifyStyle 数据结构`
                            fullScreen: false,
                            authButton: {
                                normalColor: '#ef233c', // 授权按钮正常状态背景颜色 默认值：#3479f5
                                highlightColor: '#f1011e', // 授权按钮按下状态背景颜色 默认值：#2861c5（仅ios支持）
                                title: this.$t('onePush'), // 授权按钮文案 默认值：“本机号码一键登录”
                            },
                            privacyTerms: {
                                defaultCheckBoxState: false, // 条款勾选框初始状态 默认值： true
                            },
                        },
                        success: (res) => {
                            // 获取access_token 成功
                            console.log(res.authResult)
                            uniCloud
                                .callFunction({
                                    name: 'phone',
                                    data: {
                                        access_token: res.authResult.access_token,
                                        openid: res.authResult.openid,
                                    },
                                })
                                .then((ress) => {
                                    // 获取手机号成功
                                    console.log(ress)
                                    // let phoneDecrypt = dec.encrypt(ress.result.phoneNumber)
                                    // this.oneClickLogin(phoneDecrypt)
                                    this.oneClickLogin(ress.result.phoneNumber)
                                    setTimeout(() => {
                                        uni.closeAuthView() //客户端关闭一键登录授权界面
                                    }, 500)
                                })
                                .catch((err) => {
                                    this.close()
                                    uni.closeAuthView() //客户端关闭一键登录授权界面
                                    // 处理错误
                                    console.log(err)
                                    uni.showToast({
                                        icon: 'none',
                                        title: res.errMsg,
                                    })
                                    this.showCodeLogin = false
                                })
                        },
                        fail: (res) => {
                            // 登录失败
                            console.log(res.errCode)
                            console.log(res.errMsg)
                            uni.hideLoading()
                            if (res.errCode === 30002) {
                                uni.closeAuthView()
                                // 用户点击了其他登录方式
                                this.showCodeLogin = true
                                console.log(this.showCodeLogin)
                            } else {
                                this.close()
                            }
                        },
                    })
                },
                fail: (res) => {
                    uni.hideLoading()
                    // 预登录失败
                    if (res.errCode === 30005) {
                        //不具备一键登录的使用前提，设备不支持/未开启数据流量/其他原因
                        this.showCodeLogin = true
                    } else {
                        this.close()
                        uni.showToast({
                            icon: 'none',
                            title: res.errMsg,
                        })
                    }
                    console.log(res)
                },
            })
        },

        async oneClickLogin(phone) {
            uni.showLoading({
                mask: true,
            })
            await this.$uniapi
                .oneClickLogin({
                    phone: phone,
                })
                .then((res) => {
                    uni.hideLoading()
                    if (res.code == 0) {
                        uni.showToast({
                            title: this.$t('loginSuccessful'),
                            icon: 'none',
                            duration: 2000,
                        })
                        this.loginHandle(res.data)
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none',
                            duration: 2000,
                        })
                    }
                })
                .catch((err) => {
                    uni.hideLoading()
                    uni.showToast({
                        title: err.errMsg,
                        duration: 2000,
                        icon: 'none',
                    })
                })
        },

        // 密码登录
        async _userPwdLogin() {
            let data = {
                mobile: this.phone,
                password: this.password,
            }
            uni.showLoading()
            await this.$uniapi('/passwordLogin', data, 'post')
                .then((res) => {
                    uni.hideLoading()
                    if (res.code == 0) {
                        uni.showToast({
                            icon: 'succes',
                            duration: 2000,
                        })
                        this.loginHandle(res.data)
                        this.code = ''
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none',
                        })
                    }
                })
                .catch((err) => {
                    uni.hideLoading()
                    uni.showToast({
                        title: err.errMsg,
                        icon: 'none',
                    })
                })
        },

        // 登录
        async _userLogin() {
            // 手机号
            if (!this.phone || !this.checkMobileNum(this.phone)) {
                uni.showToast({
                    title: this.$t('pleaseEnterAValidMobilePhoneNumber'),
                    icon: 'none',
                    duration: 2000,
                })
                return
            }
            if (this.checkPwdStatus) {
                if (!this.password || this.password.length < 6) {
                    uni.showToast({
                        title: this.$t('qingshurumima'),
                        icon: 'none',
                        duration: 2000,
                    })
                    return
                }
            }
            if (!this.checkPwdStatus && (!this.code || this.code.length != this.codeLength)) {
                uni.showToast({
                    title: this.$t('pleaseEnterTheCorrectVerificationCode'),
                    icon: 'none',
                    duration: 2000,
                })
                return
            }

            if (!this.select) {
                this.notagreeShow = true
                return
            }
            if (this.checkPwdStatus) {
                this._userPwdLogin()
                return
            }
            uni.showLoading({
                title: '',
            })

            let data = {
                mobile: this.phone,
                code: this.code,
                // loginType: 2,
                parent_id: uni.getStorageSync('parent_id') || '',
                type: uni.getStorageSync('type') || '',
            }
            await this.$uniapi('/login', data, 'post')
                .then((res) => {
                    console.log('res:', res)

                    uni.hideLoading()
                    if (res.code == 0) {
                        uni.showToast({
                            title: this.$t('loginSuccessful'),
                            icon: 'none',
                            duration: 2000,
                        })
                        this.loginHandle(res.data)
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none',
                            duration: 2000,
                        })
                    }
                })
                .catch((err) => {
                    uni.hideLoading()
                    uni.showToast({
                        title: err.errMsg,
                        duration: 2000,
                        icon: 'none',
                    })
                })
        },

        // 登录成功处理
        loginHandle(data) {
            uni.setStorageSync('token', data.token)
            let user = data.userInfo
            uni.setStorageSync('uid', user.id)
            uni.setStorageSync('user', user)
            uni.setStorageSync('momentsDetail', true)
            this.close()

            this.showCodeLogin = false
            let that = this
            setTimeout(() => {
                uni.$emit('loginOK', {})
                /* #ifdef APP-PLUS */
                // 获取客户clientid
                setTimeout(function () {
                    // var pinf = plus.push.getClientInfo()
                    // var clientId = (pinf && pinf.clientid) || ''
                    // if (clientId) {
                    //     that.$uniapi.userUpdateClientId({ clientId: clientId }).then((res) => {})
                    // }
                }, 2000)
                /* #endif */
            }, 1000)
        },
    },
    beforeDestroy() {
        if (this.timer) {
            clearInterval(this.timer)
        }
    },
}
</script>
<style>
.popup-box {
    /* background-image: linear-gradient(#fff, #fff5f5e5); */
    background: white;
    width: 88vw;
    border-radius: 48rpx;
    overflow: hidden;
    max-width: 780px;
}

.radio-i {
    width: 36rpx;
    height: 36rpx;
    box-sizing: border-box;
    border-radius: 50%;
    border: 2rpx solid gray;
    margin: 2rpx;
}

.wechat-login-btn {
    border-radius: 48rpx;
    padding: 18rpx 36rpx;
}

.code-button {
    /* width: 100rpx; */
    height: 60rpx;
    font-size: 22rpx;
    color: var(--app-color);
    background-color: #fff;
    border: none;
    border-radius: 40rpx;
    text-align: center;
    line-height: 60rpx;
    cursor: pointer;
    outline: none;
    letter-spacing: normal;
    /* padding: 0 !important; */
    direction: rtl;
}

.code-button::after,
.login-button::after {
    border: none !important;
}

.login-button {
    font-size: 22rpx;
    color: #fff;
    background-color: var(--app-color);
    border: none;
    border-radius: 40rpx;
    text-align: center;
    line-height: 60rpx;
    cursor: pointer;
    outline: none;
    letter-spacing: normal;
    direction: rtl;
    border-radius: 48rpx;
    font-size: 30rpx;
    padding: 4rpx 80rpx;
}
.shakeonce {
    animation: shake 0.5s ease;
    animation-iteration-count: 1; /* 确保动画只运行一次 */
}
@keyframes shake {
    0% {
        transform: translateX(0);
    }
    20% {
        transform: translateX(-7px);
    }
    40% {
        transform: translateX(7px);
    }
    60% {
        transform: translateX(-7px);
    }
    80% {
        transform: translateX(7px);
    }
    100% {
        transform: translateX(0);
    }
}
</style>